﻿using EFModel;
using IServices;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xm.Controllers;
using Y2.Dao;

namespace Serives
{
    public class Tetype : Itype
    {
        private readonly MyDBContext he;
        public Tetype(MyDBContext he)
        {
            this.he = he;
        }
        //递归查询所有权限
        public Task<string> dg()
        {
            return Task.Run(() =>
            {
                List<type> list = he.type.ToList();
                List<Tree> list2 = CreateTree(list, 0);
                return JsonConvert.SerializeObject(list2);
            });
        }
        public List<Tree> CreateTree(List<type> list, int pid)
        {
            List<Tree> list2 = new List<Tree>();
            var quan = list.Where(e => e.pid == pid);
            foreach (type item in quan)
            {
                Tree t = new Tree()
                {
                    id = item.id,
                    label = item.name,
                    icon = item.icon,
                    path = item.path,
                    children = CreateTree(list, item.id)
                };
                list2.Add(t);
            }
            return list2;
        }
        //递归查询当前id所有权限
        public Task<string> dgto(int id)
        {
            return Task.Run(() => {
                List<Tree> list2 = CreateTree1(0,id);
                return JsonConvert.SerializeObject(list2);
            });
        }
        public List<Tree> CreateTree1(int pid,int id)
        {
            List<Tree> list2 = new List<Tree>();
            var quan = he.RolPermissions.Where(e => e.RoleID == id&&e.type.pid==pid).Select(w => new { w.type.id, w.type.name, w.type.path, w.type.pid,w.type.icon,w.RoleID }).ToArray();
            foreach (var item in quan)
            {
                Tree t = new Tree()
                {
                    id = item.id,
                    label = item.name,
                    icon = item.icon,
                    path = item.path,
                    children = CreateTree1(item.id,item.RoleID)
                };
                list2.Add(t);
            }
            return list2;
        }

    }
}
